package com.buddy.learn.javasource._thread;


import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Buddy
 * @date 2021/4/18
 */
public class PrintABCUseLock {

    private int times;
    private int state;
    private Lock lock = new ReentrantLock();

    public PrintABCUseLock(int times) {
        this.times = times;
    }

    public void printA() {
        print("A", 0);
    }


    public void printB() {
        print("B", 1);
    }

    public void printC() {
        print("C", 2);
    }

    private void print(String value, int targetStat) {
        for (int i = 0; i < times; ) {
            lock.lock();
            try {
                if (state % 3 == targetStat) {
                    state++;
                    i++;
                    System.out.println(i+":"+value);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

}
